import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * @author Matthew Duane
 * Class for receiving Link Table updates from peers
 *
 */

public class GRIPReceiveServer extends Thread{
	private Point pos;
	private int port;
	private PGPeer peer;
	private ServerSocket welcomeSocket = null;
	
	public GRIPReceiveServer(Point pos, PGPeer peer, int port){
		this.pos = pos;
		this.port = port;
		this.peer = peer;
	}
	
	public void shutdown(){
		if(welcomeSocket != null)
			try {
				welcomeSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void run(){
		try{
			PSPUtil.print("GRIP Receive server " + pos + "start...listening on port " + port, peer.getPrint());
			this.welcomeSocket = new ServerSocket(port);
			
			while (true){				
				Socket connectionSocket = welcomeSocket.accept();				
						
				BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
				
				char[] num = new char[4];
				
				// Get the length of the packet
				in.read(num, 0, 4);				
				int srcLength = Integer.parseInt(new String(num), 16);
				
				// Get the destination x coordinate
				in.read(num, 0, 4);
				int srcDestx = Integer.parseInt(new String(num), 16);

				// Get the destination y coordinate
				in.read(num, 0, 4);
				int srcDesty = Integer.parseInt(new String(num), 16);
				
				// Get the destination port
				in.read(num, 0, 4);
				int srcPort = Integer.parseInt(new String(num), 16);
				
				peer.addListenSocket(srcPort, connectionSocket);
				PSPUtil.print("GRIP thread start...on port " + port, peer.getPrint());
				
				//in.read(num, 0, 4);
				//int payloadLength = Integer.parseInt(new String(num), 16);
				
				GRIPPeerThread thread = new GRIPPeerThread(in, this.peer, this.pos);
				thread.start();
				thread.join();
				
				PSPUtil.print("GRIP thread end...on port " + port, true);
				
				Thread.sleep(100);
			}
			
		}catch (Exception e){
			System.out.println(e.getMessage());
		}
	}
}
